package com.bluedot.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bluedot.controller.GetRequestJsonUtils;
import com.bluedot.dao.jedis.JedisUtil;
import com.bluedot.pojo.pack.ResultEntity;
import com.bluedot.pojo.vo.UserVO;
import com.bluedot.service.Token;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import redis.clients.jedis.Jedis;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

public class TokenFilter implements Filter {
    /**
     * 初始化方法，接收一个FilterConfig类型参数，该参数是对Filter的一些配置
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    /**
     * 销毁方法,销毁时调用
     */
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 1.获取请求路径
        String servletPath = ((HttpServletRequest) request).getRequestURI();
        // 2.获取token
        String token = ((HttpServletRequest) request).getHeader("token");
        // 3.查询黑名单
        Jedis jedis = new JedisUtil().getJedis();
        if ((token != null && jedis.get(token)==null )|| "/user/login".equals(servletPath)|| "/user/insert".equals(servletPath) || servletPath.equals("/send/message") || servletPath.equals("/request/insert") || servletPath.equals("/user/forgetPassword")
        || "/request/insertLogin".equals(servletPath)
        ){
            // 4.如果token不为空，则放入user信息到session
            if (token != null){
                //解析token
                Token token1 = new Token();
                Claims claim = token1.getTokenClaim(token);
                String subject = claim.getSubject();
                Map map = JSONObject.parseObject(subject, Map.class);
                UserVO userVO = JSONObject.parseObject(map.get("user").toString(),UserVO.class);
                HttpSession session = ((HttpServletRequest) request).getSession();
                session.setAttribute("user",userVO);
            }
            // 交给下一个过滤器或者servlet处理
            chain.doFilter(request, response);
        }else {
            // 设置响应包
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(JSON.toJSONString(ResultEntity.falseWithoutData("用户未登录(token为空或者过期)")));
            response.getWriter().flush();
        }
    }
}
